package com.anjie.powerproject.controller;


import com.anjie.powerproject.common.Result;
import com.anjie.powerproject.entity.GraphInfo;
import com.anjie.powerproject.map.GraphMap;
import com.anjie.powerproject.pojo.dto.GraphDTO;
import com.anjie.powerproject.service.DeviceService;
import com.anjie.powerproject.service.GraphInfoService;
import com.anjie.powerproject.service.RelationshipComService;
import com.anjie.powerproject.service.RelationshipService;
import com.anjie.powerproject.strategy.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("graphInfo")
@Controller
public class GraphInfoController {

    @Autowired
    private GraphInfoService graphInfoService;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private RelationshipService relationshipService;

    @Autowired
    private GraphMap graphMap;

    @Autowired
    private RelationshipComService relationshipComService;

    /**
     * 查看所有图谱列表页面,根据管理者管理楼栋进行筛选
     * @param model
     * @return
     */
    @GetMapping("/viewGraphInfo")
    public String viewGraphInfo(Model model) throws ParseException {
        List<GraphInfo> allGraphInfo = graphInfoService.getAllGraphInfo();
        model.addAttribute("graphInfoList",allGraphInfo);
        // 这里增加一个判断图谱使用时间是否闭合的判断，并将状态发回前端
        // 判断方法：如果时间段是闭合的，那么也就是说，当前遍历的时间段的起始时间的前一天和结束时间的后一天一定在其他图谱中出现过(这里是不需要考虑跨年问题的)
        List<String> startTimes = allGraphInfo.stream().map(item->item.getGraphStartTime()).collect(Collectors.toList());
        List<String> endTimes = allGraphInfo.stream().map(item->item.getGraphEndTime()).collect(Collectors.toList());
        for (GraphInfo graphInfo : allGraphInfo) {
            String time1 = DateUtils.mdFormat.format(DateUtils.plusOrMinusDay(DateUtils.mdFormat.parse(graphInfo.getGraphEndTime()), 1).getTime());
            String time2 = DateUtils.mdFormat.format(DateUtils.plusOrMinusDay(DateUtils.mdFormat.parse(graphInfo.getGraphStartTime()), -1).getTime());
            // time1 应该在 startTimes中存在，time2 应该在endTimes中存在
            if (!startTimes.contains(time1) || !endTimes.contains(time2)) {
                model.addAttribute("flag", false);
                break;
            }
        }
        if (!model.containsAttribute("flag")) {
            model.addAttribute("flag", true);
        }
        return "knowChart";
    }

    /**
     * 获取指定id的图谱信息页面
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/get/{id}")
    public String getGraphInfo(@PathVariable("id")Integer id, Model model){
        GraphInfo graphInfoById = graphInfoService.findGraphInfoById(id);
        model.addAttribute("graphInfo",graphInfoById);
        return "knowChartEdit";
    }

    /**
     * 保存一个新增图谱信息
     * @param graphInfo
     * @return
     */
    @PostMapping("/addGraphInfo")
    @ResponseBody
    public Map<String, String> addGraphInfo(GraphInfo graphInfo){
        Map<String,String> res = new HashMap();
        String message = "success";
        // 添加默认策略
        graphInfo.setUseRule(0);//图谱是否使用规则默认为否
        graphInfo.setStrategyType(1001);
        GraphInfo info = graphInfoService.addOneGraphInfo(graphInfo);
        if (info==null){
            message = "fail";
        }
        res.put("message",message);
        return res;
    }

    /**
     * 更新图谱基本信息
     * @param graphInfo
     * @return
     */
    @PostMapping("/update")
    @ResponseBody
    public Map<String, String> updateGraphInfo(GraphInfo graphInfo) throws ParseException {
//        System.out.println(graphInfo.toString());
        Map<String,String> res = new HashMap();
        String message = "success";
        GraphInfo info = graphInfoService.saveAndFlush(graphInfo);
        if (info==null){
            message = "fail";
        }
        res.put("message",message);
        return res;
    }

    /**
     * 删除一张图谱，包括删除图谱中的设备，图谱的边，还有图谱的基本信息
     * @param graphId
     * @return
     */
    @GetMapping("/delete/{graphId}")
    @ResponseBody
    public Map deleteGraphInfo(@PathVariable("graphId")Integer graphId){
        graphInfoService.deleteAllGraphInfoByGraphId(graphId);
        relationshipComService.deleteRelationshipsByGraphId(graphId);
        Map res  =new HashMap();
        res.put("message","delete_success");
        return res;
    }

    /**
     * 图谱编辑提交的处理接口，把拖拽好的图谱信息更新，包括更新边，更新设备的坐标，以及更新设备图谱标志
     * 要保证这个操作在并发的情况下安全进行，在数据库中使用乐观锁实现。
     *
     * @param graphId
     * @param xmlString
     * @return
     */
    @PostMapping("/updateGraph")
    @ResponseBody
    public Map updateGraph(Integer graphId,@RequestParam("xmlString")String xmlString){
        String s = graphInfoService.updateGraphByXmlString(graphId, xmlString);
        Map map = new HashMap();
        map.put("message",s);
        return map;
    }

    /**
     * 跳转图谱拖拽界面
     * @param graphId
     * @param model
     * @return
     */
    @GetMapping("/viewChartDrawPage/{graphId}")
    public String viewChartDrawPage(@PathVariable("graphId")Integer graphId,Model model){
        model.addAttribute("graphId",graphId);
        GraphInfo graphInfo = graphInfoService.findGraphInfoById(graphId);
        model.addAttribute("graphName",graphInfo.getGraphName());
        return "chartDraw";
    }

    @GetMapping("/checktime")
    @ResponseBody
    public Map checkTime(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime) throws ParseException {
        Map map = new HashMap();
        map.put("success", graphInfoService.checkTime(startTime, endTime));
        return map;
    }

    @GetMapping("/checktime2")
    @ResponseBody
    public Map checkTime2(@RequestParam("startTime") String startTime, @RequestParam("endTime") String endTime, @RequestParam("graphId") Integer graphId) throws ParseException {
        Map map = new HashMap();
        map.put("success", graphInfoService.checkTime2(startTime, endTime, graphId));
        return map;
    }

    @GetMapping("/getall")
    @ResponseBody
    public Result<List<GraphDTO>> getall() {
        try {
            List<GraphInfo> graphInfos = graphInfoService.getAllGraphInfo();
            return Result.ok(graphMap.toDTO(graphInfos));
        } catch (Exception ex) {
            return Result.error("获取图谱列表失败!");
        }
    }

}
